package com.example.aichat.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.aichat.entity.Conversation;
import com.example.aichat.entity.Message;
import com.example.aichat.mapper.ConversationMapper;
import com.example.aichat.mapper.MessageMapper;
import com.example.aichat.service.ChatService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Date;
import java.util.List;

/**
 * 聊天服务实现类
 */
@Service
public class ChatServiceImpl extends ServiceImpl<ConversationMapper, Conversation> implements ChatService {

    @Autowired
    private ConversationMapper conversationMapper;

    @Autowired
    private MessageMapper messageMapper;

    @Override
    @Transactional
    public Conversation createConversation(Long userId, String title) {
        Conversation conversation = new Conversation();
        conversation.setUserId(userId);
        conversation.setTitle(title);
        conversation.setStatus(1);
        conversation.setCreateTime(new Date());
        conversation.setUpdateTime(new Date());
        conversationMapper.insert(conversation);
        return conversation;
    }

    @Override
    @Transactional
    public Message sendMessage(Long conversationId, String content, String sender) {
        Message message = new Message();
        message.setConversationId(conversationId);
        message.setContent(content);
        message.setSender(sender);
        message.setStatus(1);
        message.setCreateTime(new Date());
        messageMapper.insert(message);

        // 更新对话时间
        Conversation conversation = conversationMapper.selectById(conversationId);
        if (conversation != null) {
            conversation.setUpdateTime(new Date());
            conversationMapper.updateById(conversation);
        }

        return message;
    }

    @Override
    public List<Conversation> getConversations(Long userId) {
        return conversationMapper.selectList(null);
    }

    @Override
    public List<Message> getMessages(Long conversationId) {
        return messageMapper.selectByConversationId(conversationId);
    }

    @Override
    @Transactional
    public boolean deleteConversation(Long conversationId) {
        // 先删除关联消息
        messageMapper.deleteBatchIds(messageMapper.selectByConversationId(conversationId)
                .stream().map(Message::getId).toList());
        // 再删除对话
        return conversationMapper.deleteById(conversationId) > 0;
    }
}    